#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<vector>
#include<unordered_map>
#include<queue>
using namespace std;
class Solution {
public:
    bool canFinish(int n, vector<vector<int>>& prerequisites) {
        unordered_map<int, vector<int>> as;
        vector<int> in(n);
        for (auto& e : prerequisites)
        {
            int a = e[0], b = e[1];
            as[b].push_back(a);
            in[a]++;
        }
        queue<int> aq;
        for (int i = 0; i < n; i++)
        {
            if (in[i] == 0)
            {
                aq.push(i);
            }
        }
        while (aq.size())
        {
            int w = aq.front();
            aq.pop();
            for (int a : as[w])
            {
                in[a]--;
                if (in[a] == 0)
                {
                    aq.push(a);
                }
            }
        }
        for (int i = 0; i < n; i++)
        {
            if (in[i] == 1)
            {
                return false;
            }
        }
        return true;
    }
};